//
//  HNSNGetMoneyVC.m
//  ZYManagementSystem
//
//  Created by 星道 on 17/6/15.
//  Copyright © 2017年 焕宁. All rights reserved.
//

#import "HNSNGetMoneyVC.h"
#import "MSNumberScrollAnimatedView.h"
#import "HNSNGetMoneyDetailTC.h"
#import "HNSNGetMoneyModel.h"
#import "HNSNProductOrderView.h"

@interface HNSNGetMoneyVC ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UILabel *_Money;
@property (weak, nonatomic) IBOutlet UILabel *_MoneyContent;

@property (nonatomic, weak) IBOutlet MSNumberScrollAnimatedView *numberAnimatedV;
@property (strong, nonatomic) IBOutlet UITableView *TableView;
@property (strong, nonatomic) NSMutableArray <HNSNGetMoneyModel *>*DataArr;


/**
 页码
 */
@property (nonatomic, assign) NSInteger PageNumber;

/**
 提现，放全局引用只做layer变换
 */
@property (strong, nonatomic) IBOutlet UIButton *GetMoney;
@end

@implementation HNSNGetMoneyVC



- (void)viewDidLoad {

    [super viewDidLoad];

    if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalStrongCourse) {
        
        self._MoneyContent.text = @"缴费金额*结算比例";
    }
    
    //默认页码为1
    self.PageNumber = 1;
    //预注册
    [self.TableView registerNib:[UINib nibWithNibName:[HNSNGetMoneyDetailTC description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    self.TableView.tableFooterView = [UIView new];
    self.TableView.tableHeaderView = [UIView new];
    //自动高
    self.TableView.rowHeight = UITableViewAutomaticDimension;
    self.TableView.estimatedRowHeight = 100;
    //下拉刷新
    self.TableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //网络请求
        self.RefreshData();

    }];
    //开始获得数据
    [self.TableView.mj_footer beginRefreshing];

    //提现layer变换
    self.GetMoney.layer.cornerRadius = 5.0f;
    self.GetMoney.layer.masksToBounds = YES;
    self.GetMoney.layer.borderColor = [UIColor whiteColor].CGColor;
    self.GetMoney.layer.borderWidth = 1.f;

}




#pragma mark - 网络请求
/**
 清除小红点
 */
- (void)RefreshDataForRedCycle:(HNSNGetMoneyModel *)Model
{

    // 如果没有小红点就直接打开详情
    if ([Model.isViewed isEqualToNumber:@0])
    {
        // 直接打开详情
        HNSNProductOrderView.MoneyModel(Model);
        return;
    }

    // 需要去除小红点
    NSDictionary *Params = @{
                             @"orderId"     :Model.ID,
                             @"action"      :@"changeIsViewedCourse",
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 去除小红点
            Model.isViewed = @0;

            dispatch_async(dispatch_get_main_queue(), ^{
                //通知主线程刷新
                self.EndRefresh(1);
                // 打开详情
                HNSNProductOrderView.MoneyModel(Model);
            });

        }
        else
        {
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {

        [HUD showError:NetErr];
    }];
}

/**
 网络请求
 */
- (instancetype (^)())RefreshData {

    return ^() {
        
        NSMutableDictionary *Params = [NSMutableDictionary dictionary];
        [Params setValue:[self MgrHNSNGetMoneyType:self.HNSNGetMoneyType] forKey:@"action"];//根据枚举值返回action参数
        [Params setValue:[@(self.PageNumber) stringValue] forKey:@"pageNumber"];
        
        NSString *str = [NSString stringWithFormat:@"%@",[AccountTool shareAccountTool].currentAccount.oid];
        str && str.length > 0 ? [Params setValue:[AccountTool shareAccountTool].currentAccount.oid forKey:@"oid"] : nil;
        
        [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

            //停止刷新
            self.EndRefresh(0);
            if ([Obj[@"code"] isEqualToNumber:@1000]) {

                NSArray *Arr = Obj[@"t"][@"dataList"];

                //告知没有数据了
                if (Arr.count == 0) {
                    self.EndRefresh(2);
                } else {
                    //取值
                    [Arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        //转成模型对象
                        HNSNGetMoneyModel *Model = HNSNGetMoneyModel.SetupModel(obj).SetupWithdrawMoney(Obj[@"t"][@"withdrawMoney"]);
                        [self.DataArr addObject:Model];

                        // 只要属性星币提现的才会有余额
                        if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalXingBi) {

                            [Model customParam:Obj[@"t"][@"customParam"]];
                        }

                        //取出首个模拟加载余额，只赋值一次·
                        if (self.PageNumber == 1 && idx == 0) {

                            self.SetMoney(self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalXingBi ? Model.canWithdrawCoins:Model.withdrawMoney);
                        }
                    }];
                    //通知主线程刷新
                    self.EndRefresh(1);

                    //页码加1
                    self.PageNumber += 1;
                }
            } else {
                [HUD showError:Obj[@"msg"]];
            }
        } Fail:^(NSError *error) {

            //停止刷新
            self.EndRefresh(0);
            [HUD showError:NetErr];
        }];
        return self;
    };
}


/**
 0结束刷新 1通知更新 2告知没有数据了
 */
- (instancetype (^)(NSInteger))EndRefresh {

    return ^(NSInteger Index) {

        dispatch_async(dispatch_get_main_queue(), ^{

            if (Index == 0) {
                [self.TableView.mj_footer endRefreshing]; //结束刷新
            } else if (Index == 1) {
                [self.TableView reloadData]; //通知更新
            } else if (Index == 2) {
                [self.TableView.mj_footer endRefreshingWithNoMoreData]; //告知没有数据了
            } else {

            }

        });
        return self;
    };
}




#pragma mark - tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    HNSNGetMoneyDetailTC *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    HNSNGetMoneyModel *Model = self.DataArr[indexPath.row];
    Cell.Model(Model);
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    HNSNGetMoneyModel *Model = self.DataArr[indexPath.row];

    // 检测消除小红点
    [self RefreshDataForRedCycle:Model];
}



#pragma mark - Fuction
/**
 设置金额的动画效果，参数NSString为金额
 */
- (instancetype (^)(NSNumber *))SetMoney {

    return ^(NSNumber *Money) {

        self._Money.hidden = YES;
        self.numberAnimatedV.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:38];
        self.numberAnimatedV.textColor = [UIColor whiteColor];
        self.numberAnimatedV.minLength = 2;
        NSString *Str = [NSString stringWithFormat:@"%.2f",[Money doubleValue]];
        self.numberAnimatedV.number = Str;
        [self.numberAnimatedV startAnimation];

        return self;
    };
}



/**
 提现
 */
- (IBAction)WithdrawCash:(UIButton *)sender {

    //每一个的模拟都有余额，取第一个
    HNSNGetMoneyModel *Model = self.DataArr.firstObject;
    
    if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalXingBi) {
        //如果金额小于等于0，则不操作
        if ([Model.canWithdrawCoins floatValue] <= 0) {
            //无金额提示
            [MBProgressHUD showError:@"您没有更多的金额用于提现"];
            return;
        }

    } else {
        //如果金额小于等于0，则不操作
        if ([Model.withdrawMoney floatValue] <= 0) {
            //无金额提示
            [MBProgressHUD showError:@"您没有更多的金额用于提现"];
            return;
        }
    }


    // 弹出确认框
    NSString *Price = [NSString stringWithFormat:@"您将提现￥%@元，是否继续?", self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalXingBi ? Model.canWithdrawCoins:Model.withdrawMoney];
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:Price preferredStyle:(UIAlertControllerStyleActionSheet)];
    [Alert addAction:[UIAlertAction actionWithTitle:@"继续" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {

        // 执行提现操作
        [MBProgressHUD showHUD];
        NSDictionary *Params = @{
                                 @"action":[self MgrMoneyAction],
                                 @"oid"   :[AccountTool shareAccountTool].currentAccount.oid
                                 };
        [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

            if ([Obj[@"code"] isEqualToNumber:@1000]) {

                [MBProgressHUD showSuccess:@"提现成功!"];
                //将金额置0
                self.SetMoney(@0.0);
                self.PageNumber = 1;
                [self.DataArr removeAllObjects];
                [self.TableView reloadData];
                [self.TableView.mj_footer beginRefreshing];

            } else {

                [HUD showError:Obj[@"msg"]];
            }
        } Fail:^(NSError *error) {

            [HUD showError:NetErr];
        }];
    }]];

    // 放弃
    [Alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:Alert animated:YES completion:nil];

}


/**
 根据本页枚举值返回网络请求的action参数
 */
- (NSString *)MgrHNSNGetMoneyType:(HNSNGetMoneyType)HNSNGetMoneyType
{
    if (HNSNGetMoneyType == HNSNGetMoneyTypeSN)
    {
        // SN机构
        return @"productOrderList";
    }
    else if (HNSNGetMoneyType == HNSNGetMoneyTypeNormalTaoCan)
    {
        // 普通机构 - 套餐提现
        return @"packageWithdrawOrderList";
    }
    else if (HNSNGetMoneyType == HNSNGetMoneyTypeNormalZiJin)
    {
        // 普通机构 - 资金提现
        return @"lessonOrderList";
    }
    else if (HNSNGetMoneyType == HNSNGetMoneyTypeNormalXingBi)
    {
        // 普通机构 - 星币提现
        return @"coinsOrderList";
    }
    else if (HNSNGetMoneyType == HNSNGetMoneyTypeNormalKeShiKa)
    {
        return @"orderClassCardList";
    }
    else if (HNSNGetMoneyType == HNSNGetMoneyTypeNormalKeYongJin)
    {
        return @"commissionWithdrawOrderList";
    }
    else if (HNSNGetMoneyType == HNSNGetMoneyTypeNormalStrongCourse) {
        
        return @"reinforceWithdrawOrderList";
    }
    else
    {
        return @"";
    }
}

/** 根据枚举值取得余额的字段 */
- (NSString *)YuEr:(HNSNGetMoneyType)mode {

    // 资金提现
    if (mode == HNSNGetMoneyTypeNormalZiJin ||
        mode == HNSNGetMoneyTypeSN ||
        mode == HNSNGetMoneyTypeNormalTaoCan ||
        mode == HNSNGetMoneyTypeNormalKeShiKa ||
        mode == HNSNGetMoneyTypeNormalStrongCourse) {

        return @"withdrawMoney";

    } else {

        // 星币提现
        return @"canWithdrawCoins";
    }

}

/** 根据枚举值获取资金的action */
- (NSString *)MgrMoneyAction {

    if (self.HNSNGetMoneyType == HNSNGetMoneyTypeSN)
    {
        // SN机构
        return @"packageSNWithdraw";
    }
    else if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalTaoCan)
    {
        // 普通机构 - 套餐提现
        return @"packageWithdraw";
    }
    else if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalZiJin)
    {
        // 普通机构 - 资金提现
        return @"withdraw";
    }
    else if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalXingBi)
    {
        // 普通机构 - 星币提现
        return @"withdrawCoins";
    }
    else if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalKeShiKa)
    {
        return @"classCardWithdraw";
    }
    else if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalKeYongJin)
    {
        return @"withdrawCommission";
    }
    else if (self.HNSNGetMoneyType == HNSNGetMoneyTypeNormalStrongCourse) {
        
        // 加强课提现
        return @"withdrawReinforce";
    }
    else
    {
        return @"";
    }
}

#pragma mark - Setter
- (NSMutableArray<HNSNGetMoneyModel *> *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}
@end
